﻿using Newtonsoft.Json;
using QuickPasteToolWeb.Model;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace QuickPasteToolWeb.Helper
{
    public static class HttpClientHelper
    {
        private static readonly string TokenUrl = "https://gitee.com/oauth/token";
        private static readonly string QueryUrl = "https://gitee.com/api/v5/search/repositories";
        private static readonly string RefreshTokenUrl = "https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token=";
        private static readonly HttpClient client = new HttpClient();

        public static TokenModel GetToken(UserInfo userInfo)
        {
            var result = new TokenModel();
            try
            {
                // 目标URL
                string url = TokenUrl;
                // 要发送的数据，这里是一个简单的JSON字符串
                var obj = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("grant_type","password"),
                    new KeyValuePair<string, string>("username",userInfo.UserName),
                    new KeyValuePair<string, string>("password",userInfo.Password),
                    new KeyValuePair<string, string>("scope","user_info projects"),
                    new KeyValuePair<string, string>("client_id","de2cbdb66d40357adacaa3ccb9d6066799da58b074e62fd3af95bc1786535182"),
                    new KeyValuePair<string, string>("client_secret","289a6b13cee4b51adc04fa5ae622af299aa36133c96d283588da6f4fa7299c2c"),
                };
                var content = new FormUrlEncodedContent(obj);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                HttpResponseMessage response = client.PostAsync(TokenUrl, content).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
                result = JsonConvert.DeserializeObject<TokenModel>(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            return result;
        }

        public static void RefreshToken(string refreshToken)
        {
            refreshToken = "26726ad1910330b6aa379a2922e9a3a915e71acdb519c2648045f7ad99f79730";
            var url = RefreshTokenUrl + refreshToken;
            HttpResponseMessage response = client.PostAsync(url, null).Result;
            response.EnsureSuccessStatusCode();
            string responseBody = response.Content.ReadAsStringAsync().Result;
        }

        public static void AddFile(string content)
        {
            //byte[] byteArray = Encoding.UTF8.GetBytes(content);
            //string base64String = Convert.ToBase64String(byteArray);
            //var owner = "GoodElc";
            //var repo = "QuickPasteToolDataBaseV2";
            //var path = "defaultFile/file4";
            //var url = $"https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}";
            //var postContent = new MultipartFormDataContent();

            //var token = new ByteArrayContent(Encoding.UTF8.GetBytes("abf888f4c7d60e493596b3404a9450af"));
            //token.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = '"' + "access_token" + '"' };
            //var fileContent = new ByteArrayContent(Encoding.UTF8.GetBytes(base64String));
            //fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = '"' + "content" + '"' };
            //var messageContent = new ByteArrayContent(Encoding.UTF8.GetBytes("QuickPasteToolDataBaseV2"));
            //messageContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = '"' + "message" + '"' };
            //postContent.Add(token);
            //postContent.Add(fileContent);
            //postContent.Add(messageContent);

            //var json = JsonConvert.SerializeObject(client.DefaultRequestHeaders);
            //HttpResponseMessage response = client.PostAsync(url, postContent).Result;
            //response.EnsureSuccessStatusCode();
        }

        public static void Query(string query)
        {
            client.GetAsync(query).Wait();
        }
    }
}
